package com.cqhz.quwan.ui.mine

import android.content.Intent
import android.support.v4.view.ViewPager
import android.view.View
import android.widget.ListView
import android.widget.RadioGroup
import android.widget.TextView
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.CouponEntity
import com.cqhz.quwan.service.API
import com.cqhz.quwan.service.ActionService
import com.cqhz.quwan.ui.activity.FootballLotteryActivity
import com.cqhz.quwan.ui.base.AbsAdapter
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.buy.BettingMachineActivity
import com.cqhz.quwan.ui.main.MainActivity
import com.cqhz.quwan.ui.widget.StateLayout
import com.cqhz.quwan.util.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject

class CouponsActivity :GoBackActivity(),PayEventSubscribe{

    override fun doPayFinish() {
        finish()
    }

    private val fragments = arrayListOf(
            CouponNotUsedFragment.new(),
            CouponNotDispatchedFragment.new(),
            CouponExpiredFragment.new())
    private val pagerAdapter by getSimplePagerAdapter(fragments)
    private val couponViewPager by v<ViewPager>(R.id.vp_coupon_list)
    private val couponRadioGroup by v<RadioGroup>(R.id.rg_select_coupon)
    private val titleRightText by v<TextView>(R.id.bar_right_text)
    private val selectButtons = arrayOf(R.id.rb_coupons_not_used,
            R.id.rb_coupons_not_dispatched,R.id.rb_coupons_expired)
    private var currentIndex = 0
    override fun titleBarText(): String? {
        return "我的优惠券"
    }
    override fun layout(): Int {
        return R.layout.activity_coupons
    }
    override fun initView() {
        couponViewPager.adapter = pagerAdapter
        PayEventObserver.register(this)
        titleRightText.text = "使用规则"
        titleRightText.visibility = View.VISIBLE
        titleRightText.setOnClickListener {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title,"优惠券使用规则")
            intent.putExtra(KeyContract.Url, API.YHQ_SYGZ)
            startActivity(intent)
        }
        couponViewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                currentIndex = position
                couponRadioGroup.check(selectButtons[position])
            }
        })
        couponViewPager.offscreenPageLimit = 3
        couponRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            val index = selectButtons.indexOf(checkedId)
            currentIndex = index
            couponViewPager.currentItem = index
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        PayEventObserver.unregister(this)
    }
    abstract class AbsListFragment : AbsFragment(),HasDaggerInject<ActivityInject>{
        protected val refreshLayout by findView<SmartRefreshLayout>(R.id.refreshLayout)
        protected val stateLayout by findView<StateLayout>(R.id.stateLayout)
        private val contentListView by findView<ListView>(R.id.lv_content)
        private lateinit var adapter:AbsAdapter<CouponEntity>
        private var visible = false
        private var create = false
        private var pageIndex = 1
        override fun layout(): Int {
            return R.layout.layout_listview
        }

        override fun initView() {
            adapter = object : AbsAdapter<CouponEntity>(context(),adapterItemLayout()){
                override fun handlerViewHolder(viewHolder: ViewHolder, position: Int, itemData: CouponEntity?) {
                    adapterHandler().invoke(viewHolder,position,itemData)
                }
            }
            contentListView?.adapter = adapter
            refreshLayout?.setOnRefreshListener {
                pageIndex = 1
                requestData(adapter, pageIndex)
            }
            refreshLayout?.setOnLoadMoreListener {
                requestData(adapter, ++pageIndex)
            }
            create = true
            lazyLoad()
        }
        private fun lazyLoad(){
            if (visible&&create){
                requestData(adapter, pageIndex)
            }
        }
        override fun setUserVisibleHint(isVisibleToUser: Boolean) {
            super.setUserVisibleHint(isVisibleToUser)
            visible = isVisibleToUser
            lazyLoad()
        }
        abstract fun requestData(adapter:AbsAdapter<CouponEntity>,pageIndex:Int)
        abstract fun adapterItemLayout():Int
        abstract fun adapterHandler():(AbsAdapter.ViewHolder, Int, CouponEntity?)->Unit
    }
    class CouponNotUsedFragment:AbsListFragment(){
        @Inject lateinit var modelHelper:ModelHelper
        override fun inject(t: ActivityInject?) {
            t?.inject(this)
        }

        override fun adapterItemLayout(): Int {
            return R.layout.item_coupon_not_used
        }

        override fun adapterHandler(): (AbsAdapter.ViewHolder, Int, CouponEntity?) -> Unit {
            return {viewHolder,_,entity ->
                viewHolder.setText(R.id.coupon_money,(entity?.money?:0.00).toInt().toString())
                viewHolder.setText(R.id.coupon_lottery,entity?.lotteryName)
                viewHolder.setText(R.id.coupon_overflow,"单笔订单满${(entity?.conditionMoney?:0.00).toInt()}元可用")
                viewHolder.setText(R.id.coupon_term,"有效期限至${entity?.endTime}")
                val doUseBtn = viewHolder.find<TextView>(R.id.coupon_use)
                doUseBtn.setOnClickListener {
                    val lotteryStatus = entity?.lotteryStatus?:"0"
                    when (lotteryStatus) {
                        "0" -> {
                            MainEventObserver.pushDoCheck(0)
                            val intent = Intent(context, MainActivity::class.java)
                            startActivity(intent)
                        }
                        "21" -> {
                            val intent = Intent(context, FootballLotteryActivity::class.java)
                            intent.putExtra(KeyContract.LotteryId, "21")
                            intent.putExtra(KeyContract.Position, 0)
                            startActivity(intent)
                        }
                        else -> {
                            val intent = Intent(context, BettingMachineActivity::class.java)
                            intent.putExtra(KeyContract.LotteryId, lotteryStatus)
                            intent.putExtra(KeyContract.PeriodNum, entity?.period)
                            startActivity(intent)
                        }
                    }
                }
            }
        }

        override fun requestData(adapter: AbsAdapter<CouponEntity>,pageIndex:Int) {
            val userId = APP.get()!!.loginInfo!!.userId!!
            val status = 1
            val pageNo = 1
            val pageSize = 10
            modelHelper.request(modelHelper.getService(ActionService::class.java)
                    .getCouponList(userId,status,pageIndex,pageSize),{
                if(pageIndex == 1 && it?.records?.isEmpty() == true){
                    stateLayout?.showDataNoneLayout()
                }else if(pageIndex == 1){
                    adapter.setData(it?.records)
                }else{
                    adapter.addData(it?.records)
                }
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh()
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore()
                }
            },{
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh(false)
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore(false)
                }
                showRequestError(it)
                stateLayout?.showDataNoneLayout()
            })
        }

        companion object {
            fun new() = CouponNotUsedFragment()
        }

    }
    class CouponNotDispatchedFragment:AbsListFragment(){

        @Inject lateinit var modelHelper:ModelHelper
        override fun inject(t: ActivityInject?) {
            t?.inject(this)
        }

        override fun adapterItemLayout(): Int {
            return R.layout.item_coupon_not_dispatched
        }
        override fun adapterHandler(): (AbsAdapter.ViewHolder, Int, CouponEntity?) -> Unit {
            return {viewHolder,_,entity ->
                viewHolder.setText(R.id.coupon_money,(entity?.money?:0.00).toInt().toString())
                viewHolder.setText(R.id.coupon_lottery,entity?.lotteryName)
                viewHolder.setText(R.id.coupon_overflow,"单笔订单满${(entity?.conditionMoney?:0.00).toInt()}元可用")
                viewHolder.setText(R.id.coupon_term,"将于${entity?.endTime}派发")
            }
        }

        override fun requestData(adapter: AbsAdapter<CouponEntity>,pageIndex:Int) {
            val userId = APP.get()!!.loginInfo!!.userId!!
            val status = 3
            val pageNo = 1
            val pageSize = 10
            modelHelper.request(modelHelper.getService(ActionService::class.java)
                    .getCouponList(userId,status,pageIndex,pageSize),{
                if(pageIndex == 1 && it?.records?.isEmpty() == true){
                    stateLayout?.showDataNoneLayout()
                }else if(pageIndex == 1){
                    adapter.setData(it?.records)
                }else{
                    adapter.addData(it?.records)
                }
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh()
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore()
                }
            },{
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh(false)
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore(false)
                }
                showRequestError(it)
                stateLayout?.showDataNoneLayout()
            })
        }

        companion object {
            fun new() = CouponNotDispatchedFragment()
        }

    }
    class CouponExpiredFragment:AbsListFragment(){
        @Inject lateinit var modelHelper:ModelHelper
        override fun inject(t: ActivityInject?) {
            t?.inject(this)
        }

        override fun adapterItemLayout(): Int {
            return R.layout.item_coupon_expired
        }
        override fun adapterHandler(): (AbsAdapter.ViewHolder, Int, CouponEntity?) -> Unit {
            return {viewHolder,_,entity ->
                viewHolder.setText(R.id.coupon_money,(entity?.money?:0.00).toInt().toString())
                viewHolder.setText(R.id.coupon_lottery,entity?.lotteryName)
                viewHolder.setText(R.id.coupon_overflow,"单笔订单满${(entity?.conditionMoney?:0.00).toInt()}元可用")
                viewHolder.setText(R.id.coupon_term,"有效期限至${entity?.endTime}")
            }
        }

        override fun requestData(adapter: AbsAdapter<CouponEntity>,pageIndex:Int) {

            val userId = APP.get()!!.loginInfo!!.userId!!
            val status = 2
            val pageNo = 1
            val pageSize = 10
            modelHelper.request(modelHelper.getService(ActionService::class.java)
                    .getCouponList(userId,status,pageIndex,pageSize),{
                if(pageIndex == 1 && it?.records?.isEmpty() == true){
                    stateLayout?.showDataNoneLayout()
                }else if(pageIndex == 1){
                    adapter.setData(it?.records)
                }else{
                    adapter.addData(it?.records)
                }
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh()
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore()
                }
            },{
                if (refreshLayout?.state?.isHeader!!){
                    refreshLayout?.finishRefresh(false)
                }
                if (refreshLayout?.state?.isFooter!!){
                    refreshLayout?.finishLoadMore(false)
                }
                showRequestError(it)
                stateLayout?.showDataNoneLayout()
            })
        }

        companion object {
            fun new() = CouponExpiredFragment()
        }

    }
}